﻿using Common;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using MongoDB.Bson;
using MongoDB.Driver;
using System.Diagnostics.CodeAnalysis;


namespace DB.MongoDB
{

    public static class MongoDB
    {
        public static IServiceCollection AddMongoDB([NotNull] this IServiceCollection services)
        {
            IConfiguration configuration = services.GetConfiguration();
            connStr = configuration["DBOption:ConnectString"];
            dbName = configuration["DBOption:DB"];
            services.AddScoped(typeof(IMongoDbHelper<>), typeof(MongoDbHelper<>));
            return services;
        }
        private static string connStr = null;

        private static string dbName = null;

        private static IMongoDatabase db = null;
        private static readonly object lockHelper = new object();
     
        public static IMongoDatabase GetDb()
        {

            if (db == null)
            {
                lock (lockHelper)
                {
                    if (db == null)
                    {
                        var client = new MongoClient(connStr);
                        db = client.GetDatabase(dbName);
                        
                    }
                }
            }
            return db;
        }

        public static ObjectId ToObjectId(this string source)
        {
            if (ObjectId.TryParse(source, out ObjectId id))
            {
                return id;
            }
            return id;
        }

    }




}
